import {createRouter, createWebHashHistory} from 'vue-router';
import store from '@/vuex/index';
import service from '@/utils/service';

const AppLogin = () => import('@/views/AppLogin.vue');
const AppRegister = () => import('@/views/AppRegister.vue');
const NotFound = () => import('@/views/NotFound.vue');
const routes = [
    {
        path: '/',
        redirect: '/login',
        meta: {
            requireAuth: false
        }
    },
    {
        path: '/login',
        name: 'AppLogin',
        component: AppLogin,
        meta: {
            requireAuth: false
        }
    },
    {
        path: '/register',
        name: 'AppRegister',
        component: AppRegister,
        meta: {
            requireAuth: false
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: {
            requireAuth: false
        }
    },
];
const router = createRouter({
    routes,
    history: createWebHashHistory()
});

router.beforeEach(async (to) => {
    if (to.meta.requireAuth && !store.getters.getIsLogin) {
        return '/login';
    }
    //如果已经登录且刷新页面（或第一次加载页面）
    if (store.getters.getIsLogin && store.getters.getIsFresh) {
        store.dispatch('handleSetIsFresh', false);
        await service.addRouter(router);
        return to.fullPath;
    }
});

export default router;